import axios from "axios";
import React, { Component } from "react";
import { NavLink } from "react-router-dom";
import "./Register.css";
import { notification } from "antd";

export default class Register extends Component {
  state = {
    email: "",
    pwd: "",
    name: "",
    verifyCode: "",
    countDown: 10,
    isGetBtn: true,
    isCheckPwdOk: false,
    isCheckVerifOk: false,
  };

  //获取验证码方法
  getVerify = () => {
    let { countDown, isGetBtn, email } = this.state;
    if (!isGetBtn) return;
    //验证邮箱格式
    var reg = /@+[a-zA-z]+(.com)+/;
    if (!reg.test(email)) {
      alert("邮箱格式不正确");
      return;
    }

    //过去验证码
    axios.get(`http://localhost:5500/ant/ant/Login/GetVerify?Email=${email}`).then(
      (response) => {
        console.log(response.data);
        this.setState({ verifyCode: response.data });
      },
      (err) => {
        console.log(err);
      }
    );

    this.setState({ isGetBtn: false });

    ///进入倒计时
    var iID = setInterval(() => {
      if (this.state.countDown === 0) {
        this.setState({ isGetBtn: true });
        this.setState({ countDown: 10 });
        clearInterval(iID);
      } else this.setState({ countDown: countDown-- });
    }, 1000);
  };

  postRegister = (event) => {
    event.preventDefault();

    let { email, pwd, name, isCheckPwdOk, isCheckVerifOk } = this.state;

    //输入验证
    if (email === "") {
      notification["warning"]({
        message: "未输入邮箱",
        description: "请检查邮箱输入",
      });
      return;
    }

    if (name === "") {
      notification["warning"]({
        message: "未输入姓名",
        description: "请检查姓名输入",
      });
      return;
    }

    if (!(pwd.length >= 8 && pwd.length <= 16)) {
      console.log("test");
      notification["warning"]({
        message: "密码格式不正确",
        description: "密码长度为8~16位",
      });
      return;
    }

    if (!isCheckPwdOk) {
      notification["warning"]({
        message: "两次密码输入不一致",
        description: "请检查密码输入",
      });
      return;
    }
    if (!isCheckVerifOk) {
      notification["warning"]({
        message: "验证码错误",
        description: "请重新输入验证码",
      });
      return;
    }

    //获得数据
    var data = {
      "UserRole":2,
      "UserEmail": email,
      "UserName": name,
      "UserPwd": pwd
    }

    //提交表单
    axios
      .post("http://localhost:5500/ant/ant/User/AddUser", data, {
        // headers: { "Content-Type": "multipart/form-data;" },
      })
      .then((response) => {
        if (response.status === 200) {
          notification["success"]({
            message: "注册成功",
            description: "注册成功3s后自动跳转至登陆页面",
          });
          setTimeout(() => {
            this.props.history.replace("/login");
          }, 3000);
        } else {
          notification["error"]({
            message: "注册失败",
            description: "注册失败请重试",
          });
        }
      })
      .catch((err) => console.log(err));
  };

  render() {
    let { countDown, isCheckPwdOk, verifyCode } = this.state;
    return (
      <div>
        <br />
        <br />
        <br />
        <div id="login-center-box">
          <form id="login-from" onSubmit={this.postRegister}>
            <br />
            <label htmlFor="login-from" style={{ fontSize: "30px" }}>
              注册
            </label>
            <br />
            <br />
            <div className="form-group">
              <label htmlFor="emailHelp">邮箱</label>
              <input
                type="email"
                className="form-control"
                name="account"
                aria-describedby="emailHelp"
                onChange={(input) => {
                  this.setState({ email: input.target.value });
                }}
              />
            </div>
            <div className="form-group">
              <label htmlFor="Verify">验证码</label>
              <div className="input-group mb-3">
                <input
                  type="text"
                  id="Verify"
                  className="form-control"
                  placeholder="验证码"
                  aria-label="验证码"
                  aria-describedby="button-addon2"
                  onChange={(input) => {
                    if (parseInt(input.target.value) === verifyCode) {
                      this.setState({ isCheckVerifOk: true });
                    } else {
                      this.setState({ isCheckVerifOk: false });
                    }
                  }}
                />
                <div className="input-group-append">
                  <button
                    className="btn btn-outline-secondary"
                    type="button"
                    id="button-addon2"
                    onClick={this.getVerify}
                  >
                    {!this.state.isGetBtn
                      ? `${countDown}秒后重试`
                      : "获取验证码"}
                  </button>
                </div>
              </div>
            </div>
            <div className="form-group">
              <label htmlFor="nameInput">姓名</label>
              <input
                type="text"
                className="form-control"
                name="name"
                aria-describedby="nameInput"
                onChange={(input) =>
                  this.setState({ name: input.target.value })
                }
              />
            </div>
            <div className="form-group">
              <label htmlFor="InputPassword">密码</label>
              <input
                type="password"
                className="form-control"
                id="InputPassword"
                onChange={(input) => this.setState({ pwd: input.target.value })}
              />
            </div>

            <div className="form-group">
              <label htmlFor="checkInputPassword">重复密码</label>
              <input
                type="password"
                className="form-control"
                id="checkInputPassword"
                onChange={(input) => {
                  if (input.target.value === this.state.pwd) {
                    this.setState({ isCheckPwdOk: true });
                  } else {
                    this.setState({ isCheckPwdOk: false });
                  }
                }}
              />
              <div
                style={{ display: this.state.isCheckPwdOk ? "none" : "block" }}
              >
                <p style={{ color: 'red', textAlign: 'right' }}>两次密码不一致</p>
              </div>
            </div>
            <div className="from-group row">
              <div className="col-4 offset-8">
                <NavLink className="text-center" to="/login">
                  返回登陆
                </NavLink>
              </div>
            </div>
            <br />
            <div className="from-group">
              <input
                type="submit"
                className="btn text-white "
                style={{
                  width: "100%",
                  fontSize: "20px",
                  backgroundColor: isCheckPwdOk ? "red" : "#5FB878",
                }}
                value="注册"
              />
            </div>
          </form>
        </div>
      </div>
    );
  }
}
